package dz.chuxin.app.sample.douban;

import com.trello.rxlifecycle.LifecycleTransformer;

import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by chuxin on 2016/8/29.
 */
public class ApiInterface {

    public static final String BASE_URL = "https://api.douban.com/v2/movie/";

    private MovieService movieService;

    private static ApiInterface ourInstance = new ApiInterface();

    public static ApiInterface instance() {
        return ourInstance;
    }

    private ApiInterface() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        movieService = retrofit.create(MovieService.class);
    }

    public void getTopMovie(Subscriber<List<MovieModel>> subscriber, LifecycleTransformer transformer, int start,
                            int count) {
        Observable<List<MovieModel>> observable = movieService.getTopMovie(start, count)
//                .compose(transformer)
                .map(new responseFunc<List<MovieModel>>());
        toSubscriber(observable, subscriber);
    }

    private <T> void toSubscriber(Observable<T> observable, Subscriber<T> subscriber) {
        observable
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    private class responseFunc<T> implements Func1<Response<T>, T> {

        @Override
        public T call(Response<T> tResponse) {
            return tResponse.getData();
        }
    }
}
